package com.basic.library.binding.viewadapter.image

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.basic.library.utils.ScreenUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.bumptech.glide.signature.ObjectKey
import com.tzlibrary.imageSelector.ui.loadUrl

/**
 * Created by goldze on 2017/6/18.
 */
object ViewAdapter {
    /**
     * unfixed 自适应宽或高的图
     * modify 修正 (嵌套布局中竖着的列表图有可能显示不出，原因暂不明，modify设为true修正，此时一定要加占位图，占位图是什么不重要；
     * 这个参数也能解决占位图大小和图片比例不一致的问题，见https://www.jianshu.com/p/684741f848e0#comments，https://stackoverflow.com/questions/32235413/glide-load-drawable-but-dont-scale-placeholder）
     */
    @SuppressLint("CheckResult")
    @JvmStatic
    @BindingAdapter(
        value = ["url", "placeholderRes", "crossFade", "corner", "unfixed", "modify", "noCache"],
        requireAll = false
    )
    fun setImageUri(
        imageView: ImageView,
        url: String?,
        placeholderRes: Drawable?,
        crossFade: Boolean,
        corner: Float = 0f,
        unfixed: Boolean,
        modify: Boolean,
        noCache: Boolean
    ) {
        //使用Glide框架加载图片
        if (modify) imageView.scaleType = ImageView.ScaleType.CENTER
        val options =
            if (corner == 0f) {
                if (unfixed) {//显示原图比例
                    RequestOptions()
                } else RequestOptions().transform(CenterCrop())
            } else {
                val cornerDp = ScreenUtils.dip2px(imageView.context, corner)
                if (unfixed) {//显示原图比例 加圆角
                    RequestOptions().transform(RoundedCorners(cornerDp))
                } else RequestOptions().transform(CenterCrop(), RoundedCorners(cornerDp))
            }
        Glide.with(imageView.context)
            .loadUrl(url)
            .apply(options)
            .placeholder(placeholderRes)
            .apply {
                if (noCache)
                    signature(ObjectKey(System.currentTimeMillis()))
                if (modify) {//修正图片显示不出或者比例问题
                    addListener(object : RequestListener<Drawable> {
                        override fun onLoadFailed(
                            e: GlideException?,
                            model: Any?,
                            target: Target<Drawable>?,
                            isFirstResource: Boolean
                        ): Boolean {
                            return false
                        }

                        override fun onResourceReady(
                            resource: Drawable?,
                            model: Any?,
                            target: Target<Drawable>?,
                            dataSource: DataSource?,
                            isFirstResource: Boolean
                        ): Boolean {
//                                imageView.setImageResource(0)
                            imageView.adjustViewBounds = true
                            imageView.scaleType = ImageView.ScaleType.FIT_XY
                            return false
                        }
                    })
                }
                if (crossFade)
                    transition(DrawableTransitionOptions.withCrossFade())
            }
            .into(imageView)
    }

//    @JvmStatic
//    @BindingAdapter(value = ["url2", "placeholderRes2", "crossFade2"], requireAll = false)
//    fun setImageUri(imageView: ImageView, url: String?, placeholderRes: Drawable?, crossFade: Boolean) {
//        //使用Glide框架加载图片
////        val placeholder = GlideApp.with(imageView.context)
////                .loadUrl(url)
////                .placeholder(placeholderRes)
////                .asBitmap()
//        Glide.with(imageView.context)
//                .asBitmap()
//                .load(getImageUrl(url))
//                .into(object : SimpleTarget<Bitmap>() {
//                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
//                        imageView.layoutParams = imageView.layoutParams.apply {
//                            height = 1000
//                            width = ScreenUtils.getWidth()
//                        }
//                        imageView.setImageBitmap(resource)
//                    }
//                })
//
//    }

    @JvmStatic
    @BindingAdapter(value = ["backgroundImage", "placeholderRes", "corner"], requireAll = false)
    fun setBackgroundImage(view: View, url: String?, placeholderRes: Drawable?, corner: Int) {
        //使用Glide框架加载图片
        val placeholder = Glide.with(view.context)
            .loadUrl(url)
            .transform(CenterCrop(), RoundedCorners(corner))
            .placeholder(placeholderRes)

//        if (crossFade) placeholder.transition(DrawableTransitionOptions.withCrossFade());
        placeholder.into(object : CustomViewTarget<View?, Drawable?>(view) {
            override fun onLoadFailed(errorDrawable: Drawable?) {}
            override fun onResourceReady(
                resource: Drawable,
                transition: Transition<in Drawable?>?
            ) {
                view.background = resource
            }

            override fun onResourceCleared(placeholder: Drawable?) {}
        })
    }

    @JvmStatic
    @BindingAdapter(value = ["backgroundDrawable"], requireAll = false)
    fun setBackground(view: View, drawableId: Int) {
        view.background = view.resources.getDrawable(drawableId, null)
    }

    @JvmStatic
    @BindingAdapter("android:src")
    fun setImageRes(imageView: ImageView, resID: Int) {
        if (resID != 0) {
            imageView.setImageResource(resID)
        }
    }
}